﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NI.Email.Mime;
using NI.Email.Mime.Field;
using NI.Email.Mime.Message;
using anmar.SharpMimeTools;

namespace Baggr
{
    public class Program
    {
        public static string GetBody(SharpMessage message)
        {
            return message.Body ?? string.Empty + " " + message.Subject ?? string.Empty;
        }
        static void Main(string[] args)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            var lines = File.ReadAllLines(@"d:\Projects\Diploma\Implementation\Data\TRAC\trec07p\partial\index");
            foreach (var line in lines)
            {
                data.Add(
                    Path.GetFileName(line.Split(' ')[1]),
                    line.Split(' ')[0]);
            }
            using (var feedDc = new FeedDataContext(@"Data Source=BOOKOCHKA\MSSQL2008;Initial Catalog=Feed;Integrated Security=True"))
            {
                feedDc.Connection.Open();
                Console.WriteLine("Connection is opened");
                var feedId = new Guid("AB96DCDC-A08F-4F53-A76F-D4D4553EC727");
                Guid? id = new Guid();
                var files = Directory.GetFiles(@"d:\Projects\Diploma\Implementation\Data\TRAC\trec07p\data");
                Console.WriteLine("Files are read");
                for (int i = 0; i < files.Length; i++ )
                {
                    var file = files[i];
                    Console.WriteLine();
                    using (var fileStream = File.OpenRead(file))
                    {
                        try
                        {
                            var content = GetBody(new SharpMessage(fileStream));
                            Console.WriteLine(file + ": " + content.Length + ", " + (double)i / (double)files.Length + "%");
                            feedDc.PostFeedItem(
                                feedId,
                                DateTime.Now,
                                file,
                                content,
                                file,
                                Guid.NewGuid(),
                                data[Path.GetFileName(file)].ToUpper(),
                                ref id);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            File.AppendAllText(
                                "C:\\addlog.txt",
                                file + Environment.NewLine + e + Environment.NewLine);
                        }
                    }

                }
            }
        }
    }
}
